package org.example;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.alibaba.ttl.TtlRunnable;
import com.alibaba.ttl.threadpool.TtlExecutors;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Copyright (c) 2023-2033 All Rights Reserved
 * TTL 使用
 *
 * @date: 2023/5/9
 */
public class TransmittableThreadLocalDemo {
    public static void main(String[] args) {
        testTtlRunnableGet();
        testTtlExecutorsGet();
    }

    // 1. 子线程使用 TtlRunnable.get() 封装
    public static void testTtlRunnableGet() {
        // 定义变量 TransmittableThreadLocal
        TransmittableThreadLocal<String> parent0 = new TransmittableThreadLocal<>();
        TransmittableThreadLocal<String> parent1 = new TransmittableThreadLocal<>();
        parent0.set("parent0");

        // 使用 TtlRunnable 修饰 Runnbale
        Runnable runnable = () -> {
            System.out.println(parent0.get());
            System.out.println(parent1.get());
        };
        Runnable ttlRunnable = TtlRunnable.get(runnable);

        // 在 TtlRunnable.get(task) 修饰之后set取不到
        parent1.set("parent1");

        // 线程池执行
        ExecutorService executorService = Executors.newFixedThreadPool(8);
        executorService.submit(ttlRunnable);
        executorService.shutdown();
    }

    // 2. 线程池使用 TtlExecutors.getTtlExecutorService() 修饰
    public static void testTtlExecutorsGet() {
        ThreadLocal<String> threadLocal = new TransmittableThreadLocal<>();
        threadLocal.set("123");

        ExecutorService ttlExecutorService = TtlExecutors.getTtlExecutorService(Executors.newSingleThreadExecutor());
        ttlExecutorService.execute(() -> System.err.println(threadLocal.get()));
        ttlExecutorService.shutdown();

        ExecutorService executorService = Executors.newFixedThreadPool(1);
        ExecutorService ttlExecutorService2 = TtlExecutors.getTtlExecutorService(executorService);
        ttlExecutorService2.submit(() -> { System.out.println(threadLocal.get());});
        ttlExecutorService2.shutdown();
    }
}
